<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      ></el-alert>

      <!-- 选择商品区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>请选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="cateHandlerChanged"
            change-on-select
            clearable
            filterable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="mini"
            @click="addAttrDialogVisible = true"
            >添加参数</el-button
          >

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handTagClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>

            <!-- 参数名称 -->
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="mini"
            @click="addAttrDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 动态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
             <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handTagClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>

            <!-- 参数名称 -->
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 设置添加动态参数、静态属性对话框 -->

      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addAttrDialogVisible"
        width="30%"
        @close="addAttrDialogClosedHand"
      >
        <!-- 添加表单区域 -->
        <el-form
          ref="addAttrFormRef"
          :model="addAttrForm"
          :rules="addAttrFormRules"
          label-width="100px"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addAttrForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addAttrDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParam">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改动态参数、静态属性对话框 -->
      <el-dialog
        :title="'编辑' + titleText"
        :visible.sync="editAttrDialogVisible"
        width="30%"
        @close="editAttrDialogClosedHand"
      >
        <!-- 修改参数表单区域 -->
        <el-form
          ref="editAttrFormRef"
          :model="editAttrForm"
          :rules="editAttrFormRules"
          label-width="100px"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editAttrForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editAttrDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParam">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  methods: {
      handTagClose(i,row){
            row.attr_vals.splice(i,1)
            this.saveAttrVals(row)
      },

     async saveAttrVals(row){
        // 发起网络请求，保存这次操作

        const {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`,{
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(',')
        })

        if( res.meta.status !== 200){
            return this.$message.error('新增参数项失败')
        }

        this.$message.success('新增参数项成功')

         
      },
    
    showInput(row) {
      row.inputVisible = true;
      // 让input 框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 标签添加新的内容
    async handleInputConfirm(row) {

        if(row.inputValue.trim().length===0){
            row.inputValue = ''
            row.inputVisible = false
            return
        }

        // 如果没有返回，执行到此处证明输入的是有效数据

        row.attr_vals.push(row.inputValue.trim())

        row.inputValue = ''
        row.inputVisible = false
        
        // 保存新增属性到数据库
        this.saveAttrVals(row)


    },

    // 删除参数业务逻辑
    removeParams(attr_id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.catId}/attributes/${attr_id}`
          );

          if (res.meta.status !== 200) {
            return this.$message.error("删除参数失败");
          }

          this.$message({
            type: "success",
            message: "删除成功!"
          });

          this.getDataParams();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 提交编辑参数
    editParam() {
      this.$refs.editAttrFormRef.validate(async valid => {
        if (!valid) {
          return;
        }

        const { data: res } = await this.$http.put(
          `categories/${this.catId}/attributes/${this.editAttrForm.attr_id}`,
          {
            attr_name: this.editAttrForm.attr_name,
            attr_sel: this.activeName
          }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("修改失败!");
        }

        this.$message.success("修改成功!");
        this.getDataParams();
        this.editAttrDialogVisible = false;
      });
    },

    // 显示编辑对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败!");
      }
      // 将获取到的数据赋值给编辑表单
      this.editAttrForm = res.data;

      this.editAttrDialogVisible = true;
    },

    // 添加属性
    addParam() {
      this.$refs.addAttrFormRef.validate(async valid => {
        if (!valid) {
          return;
        }
        const { data: res } = await this.$http.post(
          `categories/${this.catId}/attributes`,
          {
            attr_name: this.addAttrForm.attr_name,
            attr_sel: this.activeName
          }
        );

        if (res.meta.status !== 201) {
          return this.$message.error("添加失败");
        }

        this.$message.success("添加参数成功");
        this.addAttrDialogVisible = false;
        this.getDataParams();
      });
    },
    // 添加消息属性对话框被关闭
    addAttrDialogClosedHand() {
      this.$refs.addAttrFormRef.resetFields();
    },

    // 修改属性对话框关闭处理事件
    editAttrDialogClosedHand() {
      this.$refs.editAttrFormRef.resetFields();
    },

    // 当标签页切换被选择
    handleClick() {
      this.getDataParams();
    },

    // 获取所有商品分类
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }

      this.cateList = res.data;
    },

    // 当级联列表改变发生的事件
    async cateHandlerChanged() {
      this.getDataParams();
    },

    // 获取静态/动态数据参数
    async getDataParams() {
      // 如果选中的不是 3级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return;
      }

      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取属性失败");
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框的输入值
        item.inputValue = "";
      });

      // 这个赋值顺序不能改变，如果改变会出现点击不出现效果的问题

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }

      console.log(res.data);
    }
  },
  data() {
    return {
      cateList: [],
      cascaderProps: {
        // 配置触发选项 hover/click
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },

      selectedKeys: [],

      activeName: "many",

      manyTableData: [],

      onlyTableData: [],

      addAttrDialogVisible: false,

      editAttrDialogVisible: false,

      addAttrForm: {
        attr_name: ""
      },

      editAttrForm: {
        attr_name: ""
      },

      addAttrFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },

      editAttrFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      }
    };
  },

  created() {
    this.getCateList();
  },

  // 设置计算属性
  computed: {
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true;
      }

      return false;
    },

    catId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }

      return null;
    },

    // 设置添加参数、属性对话框的文本属性
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0px;
}
.el-cascader {
  width: 25%;
}
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 90px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
